import sys
import subprocess
import time
from statlib import stats

command = "java -cp classes/:lib/commons-cli-1.0.jar:lib/commons-lang-1.0.jar:lib/jheuristics-1.0-SNAPSHOT.jar ga.tsp.TSPGAApp"

def main(opts):
   max_generation = opts[0]
   mutation_probability = opts[1]
   xover_probability = opts[2]
   dimension = opts[3]
   tryouts = int(opts[4])
   population = opts[5]

   args = max_generation + " " + mutation_probability + " " + xover_probability + " " + dimension + " "+population
   complete_command = command + " " + args

   outs = []

   for i in range(0, tryouts):
      before = time.time()
      (age, cost) = run_process(complete_command)
      elapsed = time.time() - before
      outs.append( (int(age), int(cost), elapsed) )

   return do_stats(outs)

def do_stats(samples):

   convergence_list_time = []
   non_convergence_list_time = []

   convergence_list_age = []
   non_convergence_list_age = []

   converg_mean_time = 0
   converg_stdev_time = 0
   converg_mean_age = 0
   converg_stdev_age = 0
   propor = 0

   for tupla in samples:
      (age, cost, time) = tupla
      if int(cost) > 0:
         non_convergence_list_time.append( time )
         non_convergence_list_age.append( age )
      else:
         convergence_list_time.append( time )
         convergence_list_age.append( age )

   if (len(convergence_list_time) > 0):
      converg_mean_time = stats.mean(convergence_list_time)
      converg_stdev_time = stats.stdev(convergence_list_time)

   if (len(convergence_list_age) > 0):
      converg_mean_age = stats.mean(convergence_list_age)
      converg_stdev_age = stats.stdev(convergence_list_age)

   #if (len(non_convergence_list_time) > 0):
      #print stats.mean(non_convergence_list_time)
      #stdev = stats.stdev(non_convergence_list_time) if (len(non_convergence_list_time) > 1) else 0
      #print stdev

   #if (len(non_convergence_list_age) > 0):
      #print stats.mean(non_convergence_list_age)
      #stdev = stats.stdev(non_convergence_list_age) if (len(non_convergence_list_age) > 1) else 0
      #print stdev

   propor = str(float(len(convergence_list_time))/float(len(samples)))
 
   return str(converg_mean_time) + " " + str(converg_stdev_time) + " " + str(converg_mean_age) + " " +  str(converg_stdev_age) + " " + str(propor)


def run_process(command):
   p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
   out = p.stdout.read().strip()
   split = out.split()
   return split[1], split[2]

if __name__ == "__main__":
   opts = sys.argv[1:]
   main(opts)